package com.jianbo.proxy.conf;

import java.util.LinkedHashMap;
import java.util.Map;

import com.jianbo.proxy.util.Debug;

public class ArgsConf {

    public static ArgsConf instance;
    public static ArgsConf getInstance(String[] args) {
        if(instance == null) {
            instance = new ArgsConf(args);
        }
        return instance;
    }

    public static ArgsConf getInstance() {
        return instance;
    }

    String[] args;
    Map<String, String> map;

    public ArgsConf(String[] args) {
        this.args = args;
        map = new LinkedHashMap<>();
        this.parseArgs();
        Debug.info("parseArgs", map);
    }

    private void parseArgs() {
        for(String arg : args) {
            String[] argPair = arg.split(("="));
            String key = argPair[0];
            String value = argPair[1];
            map.put(key, value);
        }
    }

    public String getParam(String key) {
        return map.get(key);
    }

    public String getDir(String key) {
        String dir = getParam(key);
        if(dir == null) {
            throw new RuntimeException("key=" + key + "不存在");
        }
        if(!dir.endsWith("/")) {
            throw new RuntimeException("路径必须以/结尾");
        }
        dir = dir.replaceAll("\\\\", "/");
        if(dir.contains("//")) {
            throw new RuntimeException("路径不能包含//");
        }
        return dir;
    }

    public String getConfDir() {
        return getDir("confDir");
    }

    public String getFrontDir() {
        return getDir("frontDir");
    }
    
    public Integer getPort() {
        String param = getParam("port");
        if(param == null) {
            return null;
        }
        return Integer.valueOf(param);
    }
    

    public String getPropFile() {
        return getConfDir()  + "app.properties";
    }

    public String getStaticConfigFile() {
        return getConfDir()  + "static-config.js";
    }

    public String getProxyConfigFile() {
        return getConfDir()  + "proxy-config.js";
    }

    public String getFilterConfigFile() {
        return getConfDir()  + "filter-config.js";
    }

    public String getApiConfigFile() {
        return getConfDir()  + "api-config.js";
    }

    public String getCacheConfigFile() {
        return getConfDir()  + "cache-config.js";
    }

    // public String getAppConfigFile() {
    //     return getConfDir()  + "app-config.js";
    // }
}
